package foundation.tree.binaryTree;

import java.util.ArrayList;
import java.util.List;

/**
 * @author hang an
 * @since 2025/7/13
 */
public class 路径总和2 {
    List<List<Integer>> res = new ArrayList<>();

    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        f(root, targetSum, new ArrayList<>());
        return res;
    }

    public void f(TreeNode root, int need, List<Integer> path) {
        if (root == null) return;
        path.add(root.val);
        need -= root.val;
        if (root.left == null && root.right == null && need == 0) {
            res.add(new ArrayList<>(path));
        }
        f(root.left, need, path);
        f(root.right, need, path);
        path.remove(path.size() - 1);
    }
}
